#include "TestModel.h"


//TestItem::~TestItem(){
//
//}

TestModel::TestModel(){

}

void TestItem::setName(const QString &name){
    if (name_ != name){
        name_ = name;
        emit nameChanged();
    }
}
QString TestItem::getName(){
    return name_;
}

void TestItem::setValue(int value){
    if (value_ != value){
        value_ = value;
        emit valueChanged();
    }

}
int TestItem::getValue(){
    return value_;
}


//TestModel::TestModel()
//{
//
//    qDebug() << "TestModel::TestModel";
//}

//TestModel::TestModel()
//{
//
//    qDebug() << "TestModel::TestModel";
//}

void TestModel::append(const QJsonObject &item){

    qDebug() << "appnd" ;

    auto temp = new TestItem(this);
    if (!temp){
        return;
    }
    temp->setName(item.value("name").toString());
    temp->setValue(item.value("value").toInt());
    items_.append(temp);

    endResetModel();
}


QVariant TestModel::data(const QModelIndex &idx, int role )const{
    qDebug()<< "data call";
    if(!idx.isValid()){
        return QVariant();

    }
    if(role == Role::Name){
        return QVariant(items_[idx.row()]->getName());

    }
    if(role == Role::Value){
        return QVariant(items_[idx.row()]->getValue());
    }
    return QVariant();
}


int TestModel::rowCount(const QModelIndex & parent )const {
    return items_.count();
}

QHash<int , QByteArray>  TestModel::roleNames()const {
    if(roles_.empty()){

        roles_.insert(Role::Name, "name");
        roles_.insert(Role::Value, "value");
    }
    return roles_;
}



QQmlListProperty<TestItem> TestModel::datas(){

       qDebug() << "TestModel::datas ";
    return   QQmlListProperty<TestItem>(this,&items_,
                                       &TestModel::AppendFunction,
                                       &TestModel::CountFunction,
                                       &TestModel::AtFunction,
                                       &TestModel::ClearFunction);

}

void TestModel::AppendFunction(QQmlListProperty<TestItem> *items,TestItem *item){
       qDebug() << "TestModel::AppendFunction ";
    static_cast<TestItemListType*>(items->data)->append(item);
}
int TestModel::CountFunction(QQmlListProperty<TestItem> *items){

    return static_cast<TestItemListType*>(items->data)->count();

}
TestItem * TestModel::AtFunction(QQmlListProperty<TestItem> *items,int index){

    return static_cast<TestItemListType*>(items->data)->at(index);

}
void  TestModel::ClearFunction(QQmlListProperty<TestItem> *items){

    static_cast<TestItemListType*>(items->data)->clear();
}












